#include "stdafx.h"

#include "input/input.h"
#include "util/make_unique.h"

namespace natrium {
	namespace input {
		Input::Input():
			core::System("Input", core::Task::SINGLETHREADED_REPEATING)
		{
			mChan.add<video::WindowCreated>(this);
		}

		Input::~Input() {
		}

		bool Input::init() {
			//the *real* initialization can only happen after a window is created
			return System::init();
		}

		void Input::update() {
			for (auto& j: mJoysticks)
				j->update();
		}

		void Input::shutdown() {
			glfwSetKeyCallback(nullptr);
			glfwSetMousePosCallback(nullptr);
			glfwSetMouseButtonCallback(nullptr);
			glfwSetMouseWheelCallback(nullptr);
		}

		void Input::operator()(const video::WindowCreated&) {
			glfwSetKeyCallback(&Keyboard::glfwKeyboardCallback);
			glfwSetMousePosCallback(&Mouse::glfwMousePosCallback);
			glfwSetMouseButtonCallback(&Mouse::glfwMouseButtonCallback);
			glfwSetMouseWheelCallback(&Mouse::glfwMouseWheelCallback);

			//look for joysticks
			for (unsigned int i = 0; i < 16; ++i) {
				if (glfwGetJoystickParam(i, GLFW_PRESENT) == GL_TRUE) {
					mJoysticks.emplace_back(std::make_unique<Joystick>(i));
					gLog << "Joystick initialized: " << i;
				}
			}
		}

		const Keyboard& Input::getKeyboard() const {
			return mKeyboard;
		}

		const Mouse& Input::getMouse() const {
			return mMouse;
		}
	}
}